package com.zhongxi.guoyuan.view.shopCart;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.shopCart.ShoppingCartAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.rewardcoin.MallInfoResult;
import com.zhongxi.guoyuan.entity.rewardcoin.ShopCartResult;
import com.zhongxi.guoyuan.entity.rewardcoin.ShopCartResult.ToDoor;
import com.zhongxi.guoyuan.entity.shopcart.Address;
import com.zhongxi.guoyuan.entity.shopcart.Attr;
import com.zhongxi.guoyuan.entity.shopcart.RewardPayResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.view.rewardCoin.ApplyRewardActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShoppingCartActivity extends BaseActivity implements View.OnClickListener {


    private int index;
    private TextView[] tabs;
    private PullToRefreshListView lvList;

    private ImageView ivDel;
    private List<ToDoor> mListData = new ArrayList<ToDoor>();// 数据
    private ShoppingCartAdapter mListAdapter;
    private View relaReceiver;
    private TextView tvAllSelect;
    private TextView tvApply;
    private String type;
    private ShopCartResult result;
    private Map<String, String> map = new HashMap<String, String>();
    private TextView tvEdit;
    private TextView tvAddress;
    private TextView tvUserName;
    private TextView tvPhone;
    private ImageView ivMyBack;
    private boolean hasSelect;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            editCart((int)msg.obj);
        }
    };
    private Address goodsInfo;//地址信息
    private ImageView ivPerson;
    private TextView tvTips;

    /**
     * 编辑购物车商品属性
     * @param what
     */
    private void editCart(int what) {
        type = "edit";
        map.clear();
        map.put("cartid", mListData.get(what).getId());
        map.put("gid", mListData.get(what).getGoodsid());
        map.put("attrs", getAttrData());
        getServer(Url.EDIT_CART, map, "", false, null, "post");
    }

    private String getAttrData(){
        JSONObject obj = new JSONObject();
        int size = mListAdapter.getmExpandedMenuPos();
        List<Attr> attr = mListData.get(size).getAttr();
        try {
            for (int i = 0; i < attr.size(); i++) {
                obj.put(attr.get(i).getName(), attr.get(i).getValue());
            }
            mListAdapter.setmExpandedMenuPos(-1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return obj.toString();
    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_shopping_cart);
        index = getIntent().getIntExtra("flag", 1);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        ivMyBack = (ImageView) findViewById(R.id.ivBack);
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
        relaReceiver = (View) findViewById(R.id.relaReceiver);
        tvAllSelect = (TextView) findViewById(R.id.tvAllSelect);
        tvApply = (TextView) findViewById(R.id.tvApply);
        ivDel = (ImageView) findViewById(R.id.ivDel);
        tvEdit = (TextView) findViewById(R.id.tvEdit);
        tvTips = (TextView) findViewById(R.id.tvTips);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        tvAddress = (TextView) findViewById(R.id.tvAddress);
        ivPerson = (ImageView) findViewById(R.id.ivPerson);
        tabs = new TextView[2];
        tabs[0] = (TextView) findViewById(R.id.tvGet);
        tabs[1] = (TextView) findViewById(R.id.tvSend);
        if(index == 1){
            tabs[0].setSelected(true);
        }else if(index == 2){
            tabs[1].setSelected(true);
        }
        tvTitle.setText("返银超市购物车");
    }

    @Override
    protected void initData() {
        super.initData();
        mListAdapter = new ShoppingCartAdapter(context, mListData, handler);
        lvList.setAdapter(mListAdapter);
        getData();
    }

    /**
     * 获取购物车列表
     */
    private void getData() {
        type = "shoplist";
        getServer(Url.MY_SHOPCART, null, "", false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("shoplist".equals(type)){
                result = gson.fromJson(response, ShopCartResult.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                try{
                    goodsInfo = null;
                    JSONObject obj = new JSONObject(response);
                    JSONObject info = obj.getJSONObject("goodsInfo");
                    JSONObject attr = obj.getJSONObject("goodsAttr");
                    JSONObject address = obj.getJSONObject("address");
                    mListAdapter.setGoodsInfo(info, attr, address);
                    if(address.length()>0) {
                        goodsInfo = Address.parseMatch(address);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                if(index == 1) {
                    getVisible();
                }else if(index == 2){
                    postVisible();
                }
            }else if("carttopay".equals(type)){
                RewardPayResult response1 = gson.fromJson(response, RewardPayResult.class);
                MyApplication.getInstance().setSpValue(response1.getSafeobj());
                Intent intent = new Intent(context, ApplyRewardActivity.class);
                JSONObject obj = new JSONObject(response);
                try {
                    String shippingaddress = obj.getString("shippingaddress");
                    Address address = gson.fromJson(shippingaddress, Address.class);
                    intent.putExtra("address", address);
                    address.setIsflag(true);
                }catch (Exception e){
                    e.printStackTrace();
                    Address address = new Address(false);
                    intent.putExtra("address", address);
                }
                intent.putExtra("data", response);
                mListAdapter.setAllChecked(false);
                startActivityForResult(intent, 101);
            }else if("delete".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                showShortToast("删除成功！");
                mListAdapter.setAllChecked(false);
                getData();
            }else if("edit".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                showShortToast("编辑商品成功");
                getData();
            }else if("address".equals(type)){
                MallInfoResult result = gson.fromJson(response, MallInfoResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(null!=result.getData()&&!"".equals(result.getData())){
                    ivPerson.setImageResource(R.mipmap.iv_store);
                    if(null!=result.getData().getName()&&!"".equals(result.getData().getName())){
                        tvUserName.setText(result.getData().getName());
                    }else{
                        tvUserName.setText(R.string.app_name);
                    }
                    if(null!=result.getData().getMphone()&&!"".equals(result.getData().getMphone())){
                        tvPhone.setText(result.getData().getMphone());
                    }else{
                        tvPhone.setText("");
                    }
                    if(null!=result.getData().getAddress()&&!"".equals(result.getData().getAddress())){
                        tvAddress.setText(result.getData().getAddress());
                    }else{
                        tvAddress.setText("");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if(2109==result.getCode()){
                showShortToast("你购买商品部分已下架， 建议您再次确认！");
            }else if(2111== result.getCode()){
                showShortToast("编辑商品成功");
                getData();
            }else if(1001==result.getCode()){
                showShortToast("用户未登陆，请先登陆");
            }else if(2103==result.getCode()){
                showShortToast("该商品 已下架");
            }else if(2105==result.getCode()){
                showShortToast("商品信息不完善，敬请期待");
            }else if(2107==result.getCode()){
                showShortToast("商品属性编辑失败， 请重试");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        tabs[0].setOnClickListener(this);
        tabs[1].setOnClickListener(this);
        ivMyBack.setOnClickListener(this);
        ivDel.setOnClickListener(this);
        tvAllSelect.setOnClickListener(this);
        tvApply.setOnClickListener(this);
        tvEdit.setOnClickListener(this);
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == mListAdapter.getmExpandedMenuPos()) {
                    mListAdapter.setmExpandedMenuPos(-1);
                } else {
                    mListAdapter.setmExpandedMenuPos(position);
                }
                mListAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvGet:
                index = 1;
                relaReceiver.setVisibility(View.VISIBLE);
                getVisible();
                break;
            case R.id.tvSend:
                index = 2;
                postVisible();
                break;
            case R.id.ivDel:
                //删除购物车条目
                type = "delete";
                map.clear();
                map.put("cartids", getCartids());
                getServer(Url.DELETE_CART, map, "", false, null, "post");
                break;
            case R.id.tvAllSelect:
                mListAdapter.setAllChecked(!mListAdapter.isAllChecked());
                for (int i = 0; i < mListData.size(); i++) {
                    if (mListAdapter.isAllChecked()) {
                        mListData.get(i).setChecked(true);
                    } else {
                        mListData.get(i).setChecked(false);
                    }
                }
                mListAdapter.notifyDataSetChanged();
                break;
            case R.id.tvApply:
                /**
                 * 去支付
                 */
                String jsonData = getJsonData();
                if(index == 2){
                    if(null==goodsInfo||"".equals(goodsInfo)){
                        showShortToast("请先选择邮寄地址");
                    }else if(null==goodsInfo.getId()||"".equals(goodsInfo.getId())){
                        showShortToast("邮寄商品请添加邮寄地址");
                    }else{
                        if(hasSelect){
                            toPay(jsonData);
                        }else{
                            showShortToast("请先选择商品");
                        }
                    }
                }else{
                    if(hasSelect){
                        toPay(jsonData);
                    }else{
                        showShortToast("请先选择商品");
                    }
                }
                break;
            case R.id.tvEdit:
                mListAdapter.setAllChecked(false);
                Intent intent = new Intent(context, AddressListActivity.class);
                startActivityForResult(intent, 100);
                break;
        }
    }

    /**
     * 去支付
     * @param jsonData
     */
    private void toPay(String jsonData) {
        type = "carttopay";
        map.clear();
        map.put("orderInfo", jsonData);
        getServer(Url.CART_TO_PAY, map, "", false, null, "post");
    }

    /**
     * 邮寄数据解析
     */
    private void postVisible() {
        try {
            tvEdit.setVisibility(View.VISIBLE);
            tvTips.setText("邮寄详细地址电话");
            tabs[1].setSelected(true);
            tabs[0].setSelected(false);

            if (null != goodsInfo && !"".equals(goodsInfo)) {
                if (null != goodsInfo && !"".equals(goodsInfo)) {
                    if (null != goodsInfo.getUsername() && !"".equals(goodsInfo.getUsername())) {
                        tvUserName.setText(goodsInfo.getUsername());
                    } else {
                        tvUserName.setText("");
                    }
                    if (null != goodsInfo.getMphone() && !"".equals(goodsInfo.getMphone())) {
                        tvPhone.setText(goodsInfo.getMphone());
                    } else {
                        tvPhone.setText("");
                    }
                    if (null != goodsInfo.getAddress() && !"".equals(goodsInfo.getAddress())) {
                        tvAddress.setText(goodsInfo.getProvince() + goodsInfo.getCity() + goodsInfo.getPrefecture() + goodsInfo.getAddress());
                    } else {
                        tvAddress.setText("");
                    }
                }
            } else {
                relaReceiver.setVisibility(View.GONE);
            }

            mListData.clear();
            if (null != result.getShopCart())
                if (null != result.getShopCart().getPost() && result.getShopCart().getPost().size() > 0) {
                    mListData.addAll(result.getShopCart().getPost());
                }
            mListAdapter.notifyDataSetChanged();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 自提商品列表
     */
    private void getVisible() {
        try {
            tvEdit.setVisibility(View.GONE);
            tvTips.setText("提货详细地址电话");
            tabs[0].setSelected(true);
            tabs[1].setSelected(false);
            mListData.clear();
            if(null!=result.getShopCart())
            if (null != result.getShopCart().getTodoor() && result.getShopCart().getTodoor().size() > 0) {
                mListData.addAll(result.getShopCart().getTodoor());
            }
            mListAdapter.notifyDataSetChanged();

            getStoreAddress();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取店铺地址
     */
    private void getStoreAddress() {
        type = "address";
        getServer(Url.MALL_INFO, null, "", false, null, "get");
    }

    /**
     * 获取需要删除的购物车条目
     * @return
     */
    private String getCartids() {
        String str = "";
        for(int i=0; i<mListData.size(); i++){
            if(mListData.get(i).isChecked){
                if(i==0){
                    str +=mListData.get(i).getId();
                }else{
                    str +=","+mListData.get(i).getId();
                }
            }
        }
        return str;
    }

    /**
     *
     * @return
     */
    private String getJsonData() {
        JSONObject obj = new JSONObject();
        List<ToDoor> list = mListAdapter.getList();
        JSONObject todoor = new JSONObject();
        JSONObject post = new JSONObject();
        try {
            obj.put("todoor", todoor);
            obj.put("post", post);
            if(index == 1){
                obj.put("shippingid", "");
            }else if(index == 2){
                obj.put("shippingid", goodsInfo.getId());//邮寄地址id
            }
            for (int i = 0; i < list.size(); i++) {
                if (index == 1) {
                    if(list.get(i).isChecked){
                        todoor.put(list.get(i).getId(), list.get(i).getGoodsnum());
                        hasSelect = true;
                    }
                } else if (index == 2) {
                    if(list.get(i).isChecked){
                        post.put(list.get(i).getId(), list.get(i).getGoodsnum());
                        hasSelect = true;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return obj.toString();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getData();
        try {
            relaReceiver.setVisibility(View.VISIBLE);
            if (null != MyApplication.getInstance().getName() && !"".equals(MyApplication.getInstance().getName())) {
                tvUserName.setText(MyApplication.getInstance().getName());
            } else {
                relaReceiver.setVisibility(View.GONE);
            }
            if (null != MyApplication.getInstance().getUserPhone() && !"".equals(MyApplication.getInstance().getUserPhone())) {
                tvPhone.setText(MyApplication.getInstance().getUserPhone());
            } else {
                tvPhone.setText("");
            }
            if (null != MyApplication.getInstance().getAddress() && !"".equals(MyApplication.getInstance().getAddress())) {
                tvAddress.setText(MyApplication.getInstance().getAddress());
            } else {
                tvAddress.setText("");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
